// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")
const account = db.collection("account")
// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  try {
    let canJuData = await canJu.doc(event._id)
      .field({
        parentBlockDiRest: true,
        parentBlockRest: true,
        totalScoreRest: true,
        level: true,
        canPlay: true,
        win: true,
        openid: true,
        playInfo: true,
        progressTipsNum: true,
        alreadyWheel: true,
      })
      .get()

    if (canJuData.data.win) {
      return {
        code: 'winFail',
        res: null
      }
    }

    const wxContext = cloud.getWXContext()

    let isHas = await account.where({
      openid: wxContext.OPENID
    }).get()
    let myLevel = isHas.data[0].topCeng

    if (myLevel < canJuData.data.level) {
      return {
        code: 'levelFail',
        res: null
      }
    }

    if (canJuData.data.canPlay) {
      // 获取残局详细信息
      let lastPlayTime = new Date()
      let alreadyWheel = canJuData.data.alreadyWheel || false
      let canJuBlockInfo = {
        parentBlockDiRest: canJuData.data.parentBlockDiRest,
        parentBlockRest: canJuData.data.parentBlockRest,
        totalScoreRest: canJuData.data.totalScoreRest,
        progressTipsNum:canJuData.data.progressTipsNum,
        playTime: lastPlayTime,
        level: canJuData.data.level,
        alreadyWheel: alreadyWheel,
      }
      // 更新canPlay为false
      await canJu.doc(event._id)
        .update({
          data: {
            canPlay: false,
            playTime: lastPlayTime
          }
        })

      return {
        code: 'ok',
        res: canJuBlockInfo
      }
    } else {
      return {
        code: 'canPlayFail',
        res: null
      }
    }
  } catch (e) {
    return {
      code: 'fail',
      res: e
    }
  }


}
